<template>
  <div class="mileage-detail-page">

    <van-nav-bar title="我的骑行" left-arrow @click-left="router.back()" fixed />
    <!-- 总数据展示 -->
    <div class="data-card total-stats">
      <div class="total-stat">
        <div class="stat-value">{{ rideData?.rideMileageTotal || '0' }}<span class="unit">km</span></div>
        <div class="stat-label">总里程数</div>
      </div>
      <div class="stat-divider"></div>
      <div class="total-stat">
        <div class="stat-value">{{ rideData?.bendingTimesToal || '0' }}<span class="unit">次</span></div>
        <div class="stat-label">压弯</div>
      </div>
    </div>

    <!-- 月份统计图表 -->
    <div class="data-card chart-section">
      <div class="month-selector">
        <div class="month-arrow" @click="changeMonth(-1)">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="15 18 9 12 15 6"></polyline>
          </svg>
        </div>
        <div class="current-month">{{ currentMonth }}</div>
        <div class="month-arrow" @click="changeMonth(1)">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="9 18 15 12 9 6"></polyline>
          </svg>
        </div>
      </div>

      <!-- 折线图 -->
      <div class="chart-container">
        <div v-if="loading" class="loading-chart">
          <div class="loading-spinner"></div>
          <div>加载数据中...</div>
        </div>
        <div v-else-if="!hasData" class="no-data">暂无骑行数据</div>
        <div v-else class="chart" ref="chartRef"></div>
      </div>
    </div>

    <!-- 当日骑行数据 -->
    <div class="data-card day-data">
      <div class="card-header">
        <div class="section-title">当日数据</div>
        <div class="card-date">{{ formatSelectedDate() }}</div>
      </div>

      <!-- 第一行骑行数据 -->
      <div class="day-stats-row">
        <div class="day-stat">
          <div class="day-stat-value">{{ rideData?.rideMileageDay || '0' }}<span class="unit">km</span></div>
          <div class="day-stat-label">总里程数</div>
        </div>
        <div class="day-stat">
          <div class="day-stat-value">{{ rideData?.ridingTimeDayUnitMinute || '0' }}<span class="unit">min</span></div>
          <div class="day-stat-label">时长</div>
        </div>
        <div class="day-stat">
          <div class="day-stat-value">{{ rideData?.maxSpeed || '0' }}<span class="unit">km/h</span></div>
          <div class="day-stat-label">最高速度</div>
        </div>
      </div>

      <!-- 第二行骑行数据 -->
      <div class="day-stats-row">
        <div class="day-stat">
          <div class="day-stat-value">{{ rideData?.accelerationTimesDay || '0' }}<span class="unit">次</span></div>
          <div class="day-stat-label">加速</div>
        </div>
        <div class="day-stat">
          <div class="day-stat-value">{{ rideData?.brakesTimesDay || '0' }}<span class="unit">次</span></div>
          <div class="day-stat-label">急刹</div>
        </div>
        <div class="day-stat">
          <div class="day-stat-value">{{ rideData?.bendingTimesDay || '0' }}<span class="unit">次</span></div>
          <div class="day-stat-label">压弯</div>
        </div>
      </div>
    </div>

    <!-- 骑行能力雷达图 -->
    <div class="data-card radar-chart-section">
      <div class="card-header">
        <div class="section-title">骑行能力分析</div>
        <div class="share-button" @click="openSharePreview">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"></path>
            <polyline points="16 6 12 2 8 6"></polyline>
            <line x1="12" y1="2" x2="12" y2="15"></line>
          </svg>
          分享
        </div>
      </div>

      <div class="radar-container">
        <div ref="radarChartRef" class="radar-chart"></div>
      </div>
      <div class="chart-description">基于您本月的骑行数据生成</div>
    </div>

    <!-- 分享预览弹窗 -->
    <van-popup v-model:show="showShareModal" round position="bottom" :style="{ height: '80%' }" class="share-popup">
      <div class="share-header">
        <div class="share-title">骑行能力分享</div>
        <div class="close-button" @click="showShareModal = false">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </div>
      </div>

      <div class="share-content">
        <div class="preview-container" ref="previewContainerRef">
          <div class="preview-image-container" ref="sharePreviewRef">
            <div class="preview-header">
              <div class="preview-title">我的骑行能力图谱</div>
              <div class="preview-vehicle">{{ currentVehicle?.vehicleName || '我的爱车' }}</div>
            </div>
            
            <!-- 添加车辆图片 -->
            <div class="preview-vehicle-image">
              <img :src="vehicleImageUrl" alt="我的车辆" class="vehicle-image" />
              <div class="vehicle-overlay">
                <div class="vehicle-badge">{{ currentVehicle?.vehicleModel || 'ZEEHO' }}</div>
              </div>
            </div>
            
            <div class="preview-chart-container" ref="previewChartRef"></div>
            
            <div class="preview-stats">
              <div class="preview-stat-item">
                <div class="preview-stat-label">总里程</div>
                <div class="preview-stat-value">{{ rideData?.rideMileageTotal || '0' }} km</div>
              </div>
              <div class="preview-stat-item">
                <div class="preview-stat-label">最高速度</div>
                <div class="preview-stat-value">{{ rideData?.maxSpeed || '0' }} km/h</div>
              </div>
              <div class="preview-stat-item">
                <div class="preview-stat-label">本月里程</div>
                <div class="preview-stat-value">{{ rideData?.rideRocordList ? calculateMonthlyMileage() : '0' }} km
                </div>
              </div>
              <div class="preview-stat-item">
                <div class="preview-stat-label">骑行时长</div>
                <div class="preview-stat-value">{{ formatRidingTime(rideData?.ridingTimeMonthUnitMinute) }}</div>
              </div>
            </div>
            
            <!-- 添加骑行评价 -->
            <div class="riding-evaluation">
              <div class="evaluation-title">骑行评价</div>
              <div class="rating-badge" :class="getRatingClass()">{{ getRating() }}</div>
              <div class="evaluation-content">
                {{ getEvaluationText() }}
              </div>
            </div>
            
            <div class="preview-footer">
              <div class="qr-code"></div>
              <div class="brand-text">地表最强 · ZEEHO</div>
            </div>
          </div>
        </div>
        
        <!-- 分享操作按钮组 -->
        <div class="share-actions">
          <div class="share-title-small">分享方式</div>
          <div class="share-options">
            <div class="share-option" @click="saveImage">
              <div class="share-icon save-icon" :class="{ 'loading': isSavingImage }">
                <svg v-if="!isSavingImage" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path>
                  <polyline points="17 21 17 13 7 13 7 21"></polyline>
                  <polyline points="7 3 7 8 15 8"></polyline>
                </svg>
                <div v-else class="loading-spinner"></div>
              </div>
              <div class="share-label">保存图片</div>
            </div>
            <div class="share-option">
              <div class="share-icon wechat-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#07c160">
                  <path d="M8.2,15.5c-1.2,0-2.1-0.9-2.1-2.1c0-1.2,0.9-2.1,2.1-2.1c1.2,0,2.1,0.9,2.1,2.1C10.3,14.6,9.4,15.5,8.2,15.5z M13.5,9.1
                    c0-1-0.8-1.8-1.8-1.8c-1,0-1.8,0.8-1.8,1.8c0,1,0.8,1.8,1.8,1.8C12.7,10.9,13.5,10.1,13.5,9.1z M15.9,13.4c0,0.8,0.8,1.5,1.8,1.5
                      c1,0,1.8-0.7,1.8-1.5c0-0.8-0.8-1.5-1.8-1.5C16.6,11.9,15.9,12.6,15.9,13.4z M12,2C6.5,2,2,6.5,2,12s4.5,10,10,10s10-4.5,10-10
                      S17.5,2,12,2z M9.7,18.1c-0.8,0-1.4-0.2-2-0.3l-2,1l0.6-1.8c-1.4-1-2.3-2.4-2.3-4c0-2.9,2.7-5.1,6-5.1c3,0,5.5,1.8,6,4.2
                      c-0.2,0-0.4,0-0.6,0c-2.9,0-5.2,2.2-5.2,4.9c0,0.4,0.1,0.9,0.2,1.3C10.1,18.1,9.9,18.1,9.7,18.1z M18.2,20l0.4,1.5l-1.5-0.9
                      c-0.6,0.1-1.1,0.3-1.7,0.3c-2.5,0-4.5-1.7-4.5-3.9c0-2.1,2-3.9,4.5-3.9c2.4,0,4.5,1.7,4.5,3.9C19.9,18.2,19.2,19.3,18.2,20z"/>
                </svg>
              </div>
              <div class="share-label">微信好友</div>
            </div>
            <div class="share-option">
              <div class="share-icon moments-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#07c160">
                  <path d="M12,2C6.5,2,2,6.5,2,12s4.5,10,10,10s10-4.5,10-10S17.5,2,12,2z M18.7,15c-0.4,1.5-1.9,2.5-3.3,2.5c-1.3,0-2.7-0.9-4.4-1.9
                        c-1.2,1.1-2.5,1.9-3.7,1.9c-1.4,0-2.3-0.9-2.7-2.5c-0.5-2,0.7-4.5,2.9-6.1c0.3-0.2,0.7-0.5,1-0.6c0.4-0.2,0.8-0.1,1.1,0.2
                        c0.5,0.6,0.3,1.1,0,1.7c-0.2,0.3-0.4,0.6-0.6,0.9c-0.2,0.4-0.1,0.8,0.3,0.9c1.5,0.5,2.8,1.3,3.9,2.5c0.3,0.3,0.6,0.6,1,0.7
                        c0.4,0.1,0.9-0.1,1-0.5c0.2-0.6,0.3-1.3,0.4-2c0-0.3-0.2-0.7-0.3-1c-1.1-1.8-2.3-3.6-3.4-5.3c-0.1-0.2-0.4-0.4-0.6-0.5
                        c-0.4-0.1-0.8,0.1-0.9,0.5c-0.2,0.6-0.2,1.3-0.3,1.9c0,0.2,0.1,0.4,0.1,0.7c-0.3,0-0.6-0.1-0.8-0.2c-1.1-0.5-1.5-1.8-0.8-2.9
                        c0.6-1,1.5-1.2,2.7-0.9c1.9,0.6,3.1,1.9,4,3.5c0.4,0.7,0.7,1.6,1,2.3c0.1,0.4,0.2,0.8,0.2,1.2C17.9,14,18.9,14.4,18.7,15z"/>
                </svg>
              </div>
              <div class="share-label">朋友圈</div>
            </div>
            <div class="share-option">
              <div class="share-icon more-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <circle cx="12" cy="12" r="1"></circle>
                  <circle cx="19" cy="12" r="1"></circle>
                  <circle cx="5" cy="12" r="1"></circle>
                </svg>
              </div>
              <div class="share-label">更多</div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showLoadingToast, closeToast, showFailToast, showSuccessToast, Button as VanButton } from 'vant';
import { useVehicleStore } from '@/stores/vehicle';
import { getMileageDetail, getRideMonthInfo, getRidingDetail } from '@/api/vehicle';
import * as echarts from 'echarts/core';
import { BarChart, RadarChart } from 'echarts/charts';
import { GridComponent, TooltipComponent, MarkPointComponent, DataZoomComponent, LegendComponent, TitleComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import html2canvas from 'html2canvas';

// 注册ECharts需要的组件
echarts.use([
  BarChart,
  RadarChart,
  GridComponent,
  TooltipComponent,
  MarkPointComponent,
  DataZoomComponent,
  LegendComponent,
  TitleComponent,
  CanvasRenderer
]);

const router = useRouter();
const route = useRoute();
const vehicleStore = useVehicleStore();

// 当前车辆
const currentVehicle = computed(() => vehicleStore.getCurrentVehicle());

// 图表相关
const chartRef = ref(null);
const chartInstance = ref(null);
const loading = ref(true);
const hasData = ref(false);
const rideData = ref(null);

// 雷达图相关
const radarChartRef = ref(null);
let radarChartInstance = null;
const previewChartRef = ref(null);
let previewChartInstance = null;

// 分享相关
const showShareModal = ref(false);
const sharePreviewRef = ref(null);
const previewContainerRef = ref(null);
const isSavingImage = ref(false);

// 打开分享预览
const openSharePreview = () => {
  showShareModal.value = true;
};

// 车辆图片URL
const vehicleImageUrl = ref(getVehicleImage());

// 获取车辆图片
function getVehicleImage() {
  // 如果车辆有图片，则使用车辆图片
  if (currentVehicle.value?.vehicleImage) {
    return currentVehicle.value.vehicleImage;
  }
  
  // 否则根据车型选择默认图片
  const vehicleType = currentVehicle.value?.vehicleModel || '';
  
  // 根据车型选择合适的图片
  if (vehicleType.includes('CF72290')) {
    return '/src/assets/kzq/CF72290.png';
  } else if (vehicleType.includes('NB72290')) {
    return '/src/assets/kzq/NB72290.png';
  } else if (vehicleType.includes('CF72350')) {
    return '/src/assets/kzq/CF72350.jpg';
  } else {
    // 默认图片
    const images = [
      '/src/assets/kzq/CF72290.png',
      '/src/assets/kzq/NB72290.png',
      '/src/assets/kzq/CF72350.jpg'
    ];
    return images[Math.floor(Math.random() * images.length)];
  }
}

// 月份选择相关
const now = new Date();
const currentYear = ref(now.getFullYear());
const currentMonthIndex = ref(now.getMonth());
const currentMonth = computed(() => {
  return `${currentYear.value}.${String(currentMonthIndex.value + 1).padStart(2, '0')}`;
});

// 选中日期
const selectedDate = ref(null);
const selectedDayIndex = ref(-1);

// 获取里程数据
const fetchMileageData = async () => {
  if (!currentVehicle.value?.vinNo) return;

  loading.value = true;



  try {
    const response = await getMileageDetail(currentVehicle.value.vinNo);

    if (response && response.data) {
      // 保存完整的骑行数据
      rideData.value = response.data;

      hasData.value = rideData.value.rideRocordList && rideData.value.rideRocordList.length > 0;

      // 默认选中最新一天
      if (hasData.value && rideData.value.rideRocordList.length > 0) {
        selectedDayIndex.value = rideData.value.rideRocordList.length - 1;
        selectedDate.value = rideData.value.rideRocordList[selectedDayIndex.value].date;
      }

      nextTick(() => {
        initChart();
      });
    } else {
      hasData.value = false;
      showFailToast('数据获取失败');
    }
  } catch (error) {
    console.error('获取里程数据失败:', error);
    hasData.value = false;

    // 模拟数据
    rideData.value = {
      rideMileageTotal: "5089",
      bendingTimesToal: "0",
      greenContribution: "343.5",
      fate: "2133",
      rideMileageDay: "24.0",
      greenContributionDay: "1.6",
      ridingTimeDay: "0.9",
      ridingTimeDayUnitMinute: "58",
      bendingTimesDay: "0",
      maxSpeed: "66.6",
      accelerationTimesDay: "36",
      brakesTimesDay: "26",
      powerConsumptionDay: "0",
      rideRocordList: [
        { date: "2025.08.01", rideMileage: "47.7" },
        { date: "2025.08.02", rideMileage: "8.5" },
        { date: "2025.08.03", rideMileage: "45.8" },
        { date: "2025.08.04", rideMileage: "47.7" },
        { date: "2025.08.05", rideMileage: "47.8" },
        { date: "2025.08.06", rideMileage: "47.8" },
        { date: "2025.08.07", rideMileage: "47.7" },
        { date: "2025.08.08", rideMileage: "47.9" },
        { date: "2025.08.09", rideMileage: "53.6" },
        { date: "2025.08.10", rideMileage: "48.2" },
        { date: "2025.08.11", rideMileage: "24.0" }
      ]
    };

    hasData.value = true;
    selectedDayIndex.value = rideData.value.rideRocordList.length - 1;
    selectedDate.value = rideData.value.rideRocordList[selectedDayIndex.value].date;

    nextTick(() => {
      initChart();
    });
  } finally {
    loading.value = false;
    closeToast();
  }
};

// 切换月份
const changeMonth = async (direction) => {
  // 更新月份
  currentMonthIndex.value += direction;

  // 处理年份变化
  if (currentMonthIndex.value < 0) {
    currentMonthIndex.value = 11;
    currentYear.value -= 1;
  } else if (currentMonthIndex.value > 11) {
    currentMonthIndex.value = 0;
    currentYear.value += 1;
  }

  // 重新加载月份数据
  fetchMonthData();
};

// 获取月度数据
const fetchMonthData = async () => {
  if (!currentVehicle.value?.vinNo) return;

  loading.value = true;

  try {
    const response = await getRideMonthInfo(
      currentVehicle.value.vinNo,
      currentMonth.value
    );

    if (response && response.data) {
      // 保存月度骑行记录
      const monthData = response.data || [];

      if (monthData.length > 0) {
        hasData.value = true;

        // 更新图表数据但保留其他信息
        if (rideData.value) {
          rideData.value = {
            ...rideData.value,
            rideRocordList: monthData
          };
        } else {
          rideData.value = {
            rideMileageTotal: "0",
            bendingTimesToal: "0",
            rideRocordList: monthData
          };
        }

        // 默认选中最新一天
        selectedDayIndex.value = monthData.length - 1;
        selectedDate.value = monthData[selectedDayIndex.value].date;

        // 获取选中日期的详细数据
        await fetchDayData(selectedDate.value);
      } else {
        hasData.value = false;
        showFailToast('该月暂无骑行数据');
      }
    } else {
      hasData.value = false;
      showFailToast('获取月度数据失败');
    }
  } catch (error) {
    console.error('获取月度数据失败:', error);
    hasData.value = false;

    // 模拟数据
    const daysInMonth = new Date(currentYear.value, currentMonthIndex.value + 1, 0).getDate();
    const mockMonthData = Array(daysInMonth).fill().map((_, i) => {
      const day = i + 1;
      return {
        date: `${currentYear.value}.${String(currentMonthIndex.value + 1).padStart(2, '0')}.${String(day).padStart(2, '0')}`,
        rideMileage: Math.random() > 0.2 ? (Math.random() * 40 + 10).toFixed(1) : (Math.random() * 10).toFixed(1)
      };
    });

    if (rideData.value) {
      rideData.value = {
        ...rideData.value,
        rideRocordList: mockMonthData
      };
    } else {
      rideData.value = {
        rideMileageTotal: "0",
        bendingTimesToal: "0",
        rideRocordList: mockMonthData
      };
    }

    hasData.value = true;

    // 默认选中最新一天
    selectedDayIndex.value = mockMonthData.length - 1;
    selectedDate.value = mockMonthData[selectedDayIndex.value].date;
  } finally {
    loading.value = false;
    closeToast();

    // 初始化图表
    nextTick(() => {
      initChart();
    });
  }
};

// 获取特定日期的骑行数据
const fetchDayData = async (date) => {
  if (!currentVehicle.value?.vinNo || !date) return;

  try {
    const response = await getRidingDetail(
      currentVehicle.value.vinNo,
      date
    );

    if (response && response.data) {
      // 更新当日数据
      const dayData = response.data;

      // 更新rideData中的当日数据字段
      rideData.value = {
        ...rideData.value,
        rideMileageDay: dayData.rideMileageDay || '0',
        ridingTimeDayUnitMinute: dayData.ridingTimeDayUnitMinute || '0',
        maxSpeed: dayData.maxSpeed || '0',
        accelerationTimesDay: dayData.accelerationTimesDay || '0',
        brakesTimesDay: dayData.brakesTimesDay || '0',
        bendingTimesDay: dayData.bendingTimesDay || '0',
      };
    }
  } catch (error) {
    console.error('获取日数据失败:', error);
    // 处理错误，但不显示toast，因为这只是辅助数据
  }
};

// 格式化选中日期
const formatSelectedDate = () => {
  if (!selectedDate.value) return '';
  const parts = selectedDate.value.split('.');
  if (parts.length < 3) return '';
  return `${parts[0]}-${parts[1]}-${parts[2]}`;
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const parts = dateStr.split('.');
  if (parts.length < 3) return dateStr;
  return parts[2]; // 只返回日期部分
};

// 初始化图表
const initChart = () => {
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }

  if (!chartRef.value || !rideData.value?.rideRocordList) return;

  chartInstance.value = echarts.init(chartRef.value);

  // 准备图表数据
  const dates = rideData.value.rideRocordList.map(item => formatDate(item.date));
  const values = rideData.value.rideRocordList.map(item => parseFloat(item.rideMileage || 0));

  // 计算Y轴最大值，确保有足够的高度
  const maxValue = Math.max(...values);
  const yMax = maxValue < 60 ? 60 : Math.ceil(maxValue * 1.2); // 最小高度为60，否则增加20%

  // 计算刻度值
  let interval = 15;

  // 创建渐变色
  const activeItemColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: '#4361ee' },
    { offset: 1, color: '#3a0ca3' }
  ]);

  const normalItemColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: '#e6e7ff' },
    { offset: 1, color: '#dadcff' }
  ]);

  // 为选中日期准备特殊样式
  const markPoint = selectedDayIndex.value >= 0 ? {
    data: [{
      coord: [selectedDayIndex.value, values[selectedDayIndex.value]],
      value: values[selectedDayIndex.value],
      itemStyle: {
        color: activeItemColor
      },
      symbolSize: 0,
      label: { show: false }
    }],
    symbol: 'circle',
    symbolSize: 0
  } : {};

  const option = {
    grid: {
      left: '10%',
      right: '6%',
      bottom: '12%',
      top: '15%',
      containLabel: false
    },
    dataZoom: [
      {
        type: 'inside',
        start: dates.length > 10 ? Math.max(0, 100 - (10 / dates.length * 100)) : 0, // 如果数据点多，默认显示最后10个
        end: 100,
        zoomLock: false,
        throttle: 100,
        minSpan: Math.min(100, Math.max(20, 700 / dates.length))  // 动态计算最小显示比例
      },
      {
        type: 'slider',
        show: false, // 隐藏滚动条但保留功能
        height: 20,
        bottom: 0,
        start: dates.length > 10 ? Math.max(0, 100 - (10 / dates.length * 100)) : 0,
        end: 100
      }
    ],
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#eaeaea'
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#666',
        fontSize: 12,
        fontWeight: 400,
        margin: 10
      }
    },
    yAxis: {
      type: 'value',
      name: 'km',
      nameTextStyle: {
        padding: [0, 0, 0, 5],
        fontSize: 12,
        color: '#999'
      },
      max: yMax,
      interval: interval,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#f5f5f5',
          type: 'dashed',
          width: 1
        }
      },
      axisLabel: {
        color: '#999',
        fontSize: 12,
        formatter: function (value) {
          return value === 0 ? '0' : value;
        }
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        const data = params[0];
        return `${data.name}日: ${data.value} km`;
      },
      backgroundColor: 'rgba(50, 50, 50, 0.7)',
      borderWidth: 0,
      textStyle: {
        color: '#fff'
      },
      position: function (pos, params, dom, rect, size) {
        return [pos[0] - 30, pos[1] - 60]; // 在柱状图上方显示
      },
      extraCssText: 'border-radius:4px; padding: 6px 10px;'
    },
    series: [{
      type: 'bar',
      data: values,
      barWidth: '50%',
      itemStyle: {
        color: function (params) {
          // 选中的日期使用特殊颜色
          return params.dataIndex === selectedDayIndex.value ? activeItemColor : normalItemColor;
        },
        borderRadius: [4, 4, 0, 0]
      },
      markPoint: markPoint,
      emphasis: {
        itemStyle: {
          color: activeItemColor
        }
      },
      animation: true,
      animationDuration: 600,
      animationEasing: 'elasticOut',
      label: {
        show: true,
        position: 'top',
        fontSize: 10,
        color: '#666',
        formatter: function (params) {
          const val = parseFloat(params.value);
          return val > 0 ? val.toFixed(1) : '';
        },
        distance: 5
      }
    }]
  };

  chartInstance.value.setOption(option);

  // 注册点击事件
  chartInstance.value.on('click', async (params) => {
    if (params.componentType === 'series') {
      selectedDayIndex.value = params.dataIndex;
      selectedDate.value = rideData.value.rideRocordList[params.dataIndex].date;

      // 获取选中日期的详细数据
      await fetchDayData(selectedDate.value);

      // 更新图表
      // initChart();
    }
  });

  // 自适应大小
  window.addEventListener('resize', () => {
    chartInstance.value && chartInstance.value.resize();
  });
};

// 计算雷达图数据
const calculateRadarData = () => {
  if (!rideData.value) return null;

  // 使用当前车辆数据，构造雷达图所需的数据
  return {
    maxSpeed: parseFloat(rideData.value?.maxSpeed || 0), // 最高速度
    avgSpeed: parseFloat(rideData.value?.avgVelocityMonth || 0), // 平均速度
    mileage: parseFloat(rideData.value?.rideMileageMonth || 0), // 里程
    ridingTime: parseFloat(rideData.value?.ridingTimeMonthUnitMinute || 0), // 骑行时间
    bendings: parseFloat(rideData.value?.bendingTimesDay || 0), // 压弯次数
    acceleration: parseFloat(rideData.value?.accelerationTimesDay || 0), // 加速次数
  };
};

// 初始化雷达图
const initRadarChart = (container, isPreview = false) => {
  const chartContainer = container;
  if (!chartContainer) return;

  // 如果已经存在图表实例，销毁它
  let chartInstance = isPreview ? previewChartInstance : radarChartInstance;
  if (chartInstance) {
    chartInstance.dispose();
  }

  // 创建新的图表实例
  chartInstance = echarts.init(chartContainer);
  if (isPreview) {
    previewChartInstance = chartInstance;
  } else {
    radarChartInstance = chartInstance;
  }

  // 生成雷达图数据和配置
  const data = calculateRadarData();
  if (!data) return;

  // 雷达图最大值设置（根据实际数据调整）
  const maxValues = {
    maxSpeed: 100,     // 最高速度 km/h
    avgSpeed: 60,      // 平均速度 km/h
    mileage: 500,      // 里程 km
    ridingTime: 1000,  // 骑行时间 min
    bendings: 100,     // 压弯次数
    acceleration: 100  // 加速次数
  };

  // 计算百分比值（用于雷达图显示）
  const percentageData = [
    (data.maxSpeed / maxValues.maxSpeed) * 100,
    (data.avgSpeed / maxValues.avgSpeed) * 100,
    (data.mileage / maxValues.mileage) * 100,
    (data.ridingTime / maxValues.ridingTime) * 100,
    (data.bendings / maxValues.bendings) * 100,
    (data.acceleration / maxValues.acceleration) * 100
  ];
  
  // 根据评级选择不同的颜色
  const rating = getRating();
  let mainColor, gradientColor1, gradientColor2;
  
  switch(rating) {
    case 'S':
      mainColor = '#ff4e50';
      gradientColor1 = 'rgba(255, 78, 80, 0.8)';
      gradientColor2 = 'rgba(255, 154, 0, 0.1)';
      break;
    case 'A':
      mainColor = '#4361ee';
      gradientColor1 = 'rgba(67, 97, 238, 0.8)';
      gradientColor2 = 'rgba(58, 12, 163, 0.1)';
      break;
    case 'B':
      mainColor = '#2ecc71';
      gradientColor1 = 'rgba(46, 204, 113, 0.8)';
      gradientColor2 = 'rgba(39, 174, 96, 0.1)';
      break;
    default:
      mainColor = '#3498db';
      gradientColor1 = 'rgba(52, 152, 219, 0.8)';
      gradientColor2 = 'rgba(41, 128, 185, 0.1)';
  }

  const option = {
    backgroundColor: 'transparent',
    color: [mainColor],
    radar: {
      indicator: [
        { name: '最高速度', max: 100 },
        { name: '平均速度', max: 100 },
        { name: '骑行里程', max: 100 },
        { name: '骑行时长', max: 100 },
        { name: '压弯技巧', max: 100 },
        { name: '加速能力', max: 100 }
      ],
      center: ['50%', '50%'],
      radius: isPreview ? '70%' : '60%',
      splitNumber: 4,
      shape: 'polygon',
      axisName: {
        color: '#333',
        fontSize: isPreview ? 10 : 11,
        padding: [3, 5],
        fontWeight: isPreview ? 'bold' : 'normal'
      },
      splitArea: {
        show: true,
        areaStyle: {
          color: ['#f9f9f9', '#f1f1f1', '#e9e9e9', '#e1e1e1']
        }
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#ddd'
        }
      }
    },
    series: [{
      type: 'radar',
      data: [
        {
          value: percentageData,
          name: '骑行能力',
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: mainColor
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: gradientColor1 },
              { offset: 1, color: gradientColor2 }
            ])
          },
          lineStyle: {
            color: mainColor,
            width: 2,
            type: isPreview ? 'solid' : 'solid'
          }
        }
      ]
    }]
  };

  chartInstance.setOption(option);
};

// 计算本月总里程
const calculateMonthlyMileage = () => {
  if (!rideData.value?.rideRocordList || rideData.value.rideRocordList.length === 0) return '0';

  const total = rideData.value.rideRocordList.reduce((sum, item) => {
    return sum + parseFloat(item.rideMileage || 0);
  }, 0);

  return total.toFixed(1);
};

// 格式化骑行时间
const formatRidingTime = (minutes) => {
  if (minutes === null || minutes === undefined) return '0 min';
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  return `${hours}h ${remainingMinutes}min`;
};

// 生成骑行评价
const generateRidingEvaluation = () => {
  if (!rideData.value) return '暂无骑行数据，无法生成评价。';

  const maxSpeed = parseFloat(rideData.value.maxSpeed || 0);
  const monthlyMileage = parseFloat(calculateMonthlyMileage());
  const totalMileage = parseFloat(rideData.value.rideMileageTotal || 0);
  const ridingTime = parseFloat(rideData.value.ridingTimeMonthUnitMinute || 0);
  const bendings = parseFloat(rideData.value.bendingTimesToal || 0);

  // 计算总体评分（满分100分）
  let totalScore = 0;
  
  // 最高速度评分（最高20分）
  const maxSpeedScore = Math.min(maxSpeed / 100 * 20, 20);
  totalScore += maxSpeedScore;
  
  // 月里程评分（最高20分）
  const monthlyMileageScore = Math.min(monthlyMileage / 500 * 20, 20);
  totalScore += monthlyMileageScore;
  
  // 总里程评分（最高20分）
  const totalMileageScore = Math.min(totalMileage / 5000 * 20, 20);
  totalScore += totalMileageScore;
  
  // 骑行时长评分（最高20分）
  const ridingTimeScore = Math.min(ridingTime / 1000 * 20, 20);
  totalScore += ridingTimeScore;
  
  // 压弯技巧评分（最高20分）
  const bendingsScore = Math.min(bendings / 50 * 20, 20);
  totalScore += bendingsScore;
  
  // 根据总评分给出评级和评价
  let rating, evaluation;
  
  if (totalScore >= 80) {
    rating = 'S';
    evaluation = '您是一位经验丰富的骑手，对车辆有着出色的掌控能力和骑行经验。您的骑行数据显示出优秀的技巧和耐力，继续保持!';
  } else if (totalScore >= 60) {
    rating = 'A';
    evaluation = '您是一位熟练的骑手，具有良好的骑行习惯和技巧。通过更多的练习，您可以进一步提升自己的骑行能力!';
  } else if (totalScore >= 40) {
    rating = 'B';
    evaluation = '您已经具备了不错的骑行基础，但仍有提升空间。建议多关注骑行姿势和技巧，提高骑行效率和安全性!';
  } else {
    rating = 'C';
    evaluation = '您正处于骑行技巧的学习阶段。建议从基础骑行姿势和安全骑行开始，逐步积累骑行经验!';
  }

  return `骑行评级: ${rating}\n${evaluation}`;
};

// 获取骑行评级
const getRating = () => {
  if (!rideData.value) return 'C';

  const maxSpeed = parseFloat(rideData.value.maxSpeed || 0);
  const monthlyMileage = parseFloat(calculateMonthlyMileage());
  const totalMileage = parseFloat(rideData.value.rideMileageTotal || 0);
  const ridingTime = parseFloat(rideData.value.ridingTimeMonthUnitMinute || 0);
  const bendings = parseFloat(rideData.value.bendingTimesToal || 0);

  // 计算总体评分（满分100分）
  let totalScore = 0;
  
  // 最高速度评分（最高20分）
  totalScore += Math.min(maxSpeed / 100 * 20, 20);
  
  // 月里程评分（最高20分）
  totalScore += Math.min(monthlyMileage / 500 * 20, 20);
  
  // 总里程评分（最高20分）
  totalScore += Math.min(totalMileage / 5000 * 20, 20);
  
  // 骑行时长评分（最高20分）
  totalScore += Math.min(ridingTime / 1000 * 20, 20);
  
  // 压弯技巧评分（最高20分）
  totalScore += Math.min(bendings / 50 * 20, 20);
  
  // 根据总评分给出评级
  if (totalScore >= 80) return 'S';
  if (totalScore >= 60) return 'A';
  if (totalScore >= 40) return 'B';
  return 'C';
};

// 获取评级对应的样式类
const getRatingClass = () => {
  return getRating();
};

// 获取评价文本
const getEvaluationText = () => {
  if (!rideData.value) return '暂无骑行数据，无法生成评价。';

  const rating = getRating();
  
  switch(rating) {
    case 'S':
      return '您是一位经验丰富的骑手，对车辆有着出色的掌控能力和骑行经验。您的骑行数据显示出优秀的技巧和耐力，继续保持!';
    case 'A':
      return '您是一位熟练的骑手，具有良好的骑行习惯和技巧。通过更多的练习，您可以进一步提升自己的骑行能力!';
    case 'B':
      return '您已经具备了不错的骑行基础，但仍有提升空间。建议多关注骑行姿势和技巧，提高骑行效率和安全性!';
    default:
      return '您正处于骑行技巧的学习阶段。建议从基础骑行姿势和安全骑行开始，逐步积累骑行经验!';
  }
};

// 保存图片
const saveImage = async () => {
  if (!sharePreviewRef.value) return;

  try {
    isSavingImage.value = true;
    showLoadingToast({
      message: '生成图片中...',
      forbidClick: true,
      duration: 0,
    });

    // 确保雷达图已经渲染
    await nextTick();
    
    // 确保图片已加载
    const images = sharePreviewRef.value.querySelectorAll('img');
    if (images.length > 0) {
      await Promise.all(Array.from(images).map(img => {
        if (img.complete) return Promise.resolve();
        return new Promise(resolve => {
          img.onload = resolve;
          img.onerror = resolve; // 即使加载失败也继续执行
        });
      }));
    }

    // 截取预览区域为图片
    const canvas = await html2canvas(sharePreviewRef.value, {
      useCORS: true,
      scale: 2,
      backgroundColor: '#fff',
      allowTaint: true,
      logging: false
    });

    // 转换为图片URL
    const imgData = canvas.toDataURL('image/png');

    // 创建下载链接
    const link = document.createElement('a');
    link.href = imgData;
    link.download = `${currentVehicle.value?.vehicleName || '我的爱车'}_骑行图谱.png`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    showSuccessToast('图片已保存');
  } catch (error) {
    console.error('生成图片失败:', error);
    showFailToast('保存图片失败');
  } finally {
    closeToast();
    isSavingImage.value = false;
  }
};

// 打开分享预览
watch(showShareModal, (show) => {
  if (show) {
    nextTick(() => {
      // 在预览弹窗中初始化雷达图
      initRadarChart(previewChartRef.value, true);
    });
  }
});

// 监听数据变化，更新雷达图
watch(rideData, () => {
  nextTick(() => {
    if (radarChartRef.value) {
      initRadarChart(radarChartRef.value);
    }
  });
}, { deep: true });

// 监听当前车辆变化，更新图片
watch(currentVehicle, () => {
  vehicleImageUrl.value = getVehicleImage();
});

// 初始化
onMounted(async () => {
  // 检查是否有指定的车辆
  const { vinNo } = route.query;
  if (vinNo) {
    // 先获取初始数据
    await fetchMileageData();

    // 初始化雷达图
    nextTick(() => {
      initRadarChart(radarChartRef.value);
    });
  } else {
    // 如果没有指定车辆，则返回首页
    router.replace('/');
  }

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    if (chartInstance.value) {
      chartInstance.value.resize();
    }
    if (radarChartInstance) {
      radarChartInstance.resize();
    }
  });
});

onUnmounted(() => {
  // 清理图表实例，避免内存泄漏
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }
  if (radarChartInstance) {
    radarChartInstance.dispose();
  }
  if (previewChartInstance) {
    previewChartInstance.dispose();
  }

  window.removeEventListener('resize', () => { });
});
</script>

<style lang="scss" scoped>
.mileage-detail-page {
  height: 100%;
  background-color: #f7f7fa;
  padding-top: 46px;
  overflow: auto;
  font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Arial, sans-serif;

  // 隐藏滚动条
  &::-webkit-scrollbar {
    display: none;
  }
}

.page-header {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 15px 16px;
  position: relative;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  .back-icon {
    position: absolute;
    left: 16px;
    top: 50%;
    transform: translateY(-50%);
    color: #333;
    cursor: pointer;

    &:active {
      opacity: 0.7;
    }
  }

  .page-title {
    flex: 1;
    text-align: center;
    font-size: 18px;
    font-weight: 600;
    color: #111;
  }
}

.nav-cards {
  display: flex;
  background-color: #fff;
  padding: 15px 0 12px;
  margin-bottom: 12px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  .nav-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .nav-icon {
      width: 44px;
      height: 44px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 6px;
      color: #4361ee;
      background-color: #f0f4ff;
      border-radius: 50%;

      &:active {
        background-color: #e6ebff;
      }
    }

    .nav-text {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }
  }
}

.data-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin: 0 12px 12px;
  overflow: hidden;
}

.total-stats {
  display: flex;
  padding: 12px 7px;

  .total-stat {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;

    .stat-value {
      font-size: 20px;
      font-weight: 700;
      color: #111;
      margin-bottom: 2px;

      .unit {
        font-size: 14px;
        font-weight: normal;
        margin-left: 2px;
        color: #666;
      }
    }

    .stat-label {
      font-size: 13px;
      color: #666;
    }
  }

  .stat-divider {
    width: 1px;
    height: 40px;
    background-color: #eee;
    margin: 0 20px;
    align-self: center;
  }
}

.chart-section {
  padding: 10px;

  .month-selector {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 5px;

    .month-arrow {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      color: #4361ee;
      border-radius: 50%;

      &:active {
        background-color: #f0f4ff;
        transform: scale(0.95);
      }
    }

    .current-month {
      font-size: 16px;
      font-weight: 600;
      margin: 0 15px;
      color: #333;
      min-width: 80px;
      text-align: center;
    }
  }

  .chart-container {
    height: 220px;

    .loading-chart {
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #666;
      font-size: 14px;

      .loading-spinner {
        width: 30px;
        height: 30px;
        border: 3px solid #f0f4ff;
        border-top: 3px solid #4361ee;
        border-radius: 50%;
        margin-bottom: 10px;
        animation: spin 1s linear infinite;
      }

      @keyframes spin {
        0% {
          transform: rotate(0deg);
        }

        100% {
          transform: rotate(360deg);
        }
      }
    }

    .no-data {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #999;
      font-size: 14px;
    }

    .chart {
      height: 100%;
      width: 100%;
    }
  }
}

.day-data {
  .card-header {
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .card-date {
      font-size: 14px;
      color: #4361ee;
      font-weight: 500;
    }
  }

  .day-stats-row {
    display: flex;
    padding: 10px 0;

    &:not(:last-child) {
      border-bottom: 1px solid #f0f0f0;
    }

    .day-stat {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;

      .day-stat-value {
        font-size: 20px;
        font-weight: 700;
        color: #333;

        .unit {
          font-size: 12px;
          font-weight: normal;
          margin-left: 2px;
          color: #666;
        }
      }

      .day-stat-label {
        font-size: 13px;
        color: #666;
      }
    }
  }
}

// 雷达图部分
.radar-chart-section {
  padding: 16px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .share-button {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #4361ee;
      cursor: pointer;

      svg {
        margin-right: 4px;
      }

      &:active {
        opacity: 0.8;
      }
    }
  }

  .radar-container {
    height: 220px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fafafa;
    border-radius: 8px;
    overflow: hidden;

    .radar-chart {
      width: 100%;
      height: 100%;
    }
  }

  .chart-description {
    margin-top: 10px;
    text-align: center;
    font-size: 12px;
    color: #666;
  }
}

// 分享预览弹窗
.share-popup {
  overflow: hidden;
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;

  .share-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #eee;

    .share-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    .close-button {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      background-color: #f5f5f5;
      cursor: pointer;

      &:active {
        background-color: #e5e5e5;
      }
    }
  }

  .share-content {
    display: flex;
    flex-direction: column;
    height: calc(100% - 64px);

    .preview-container {
      flex: 1;
      overflow-y: auto;
      padding: 20px;
      display: flex;
      justify-content: center;
      align-items: flex-start;
      background-color: #f5f5f5;

      .preview-image-container {
        background-color: #fff;
        padding: 20px;
        border-radius: 12px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        width: 320px;
        position: relative; /* Added for positioning overlay */

        .preview-header {
          text-align: center;
          margin-bottom: 15px;

          .preview-title {
            font-size: 20px;
            font-weight: 700;
            margin-bottom: 5px;
            color: #333;
            background: linear-gradient(90deg, #4361ee, #3a0ca3);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
          }

          .preview-vehicle {
            font-size: 14px;
            color: #666;
            font-weight: 500;
          }
        }

        .preview-vehicle-image {
          width: 100%;
          height: 140px;
          display: flex;
          justify-content: center;
          align-items: center;
          background-color: #f5f5f5;
          border-radius: 10px;
          margin-bottom: 15px;
          overflow: hidden;
          position: relative; /* Added for positioning overlay */
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

          .vehicle-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .vehicle-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 10px;
            background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
            display: flex;
            justify-content: flex-end;
            align-items: flex-end;

            .vehicle-badge {
              background-color: rgba(67, 97, 238, 0.9);
              color: white;
              font-size: 12px;
              font-weight: 600;
              padding: 4px 8px;
              border-radius: 4px;
              box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            }
          }
        }

        .preview-chart-container {
          height: 220px;
          margin-bottom: 15px;
          background-color: #fafafa;
          border-radius: 10px;
          padding: 10px;
          box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.05);
        }

        .preview-stats {
          background-color: #f9f9f9;
          border-radius: 10px;
          padding: 12px;
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 12px;
          box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.05);

          .preview-stat-item {
            .preview-stat-label {
              font-size: 12px;
              color: #666;
              margin-bottom: 2px;
            }

            .preview-stat-value {
              font-size: 16px;
              font-weight: 600;
              color: #4361ee;
            }
          }
        }

        .riding-evaluation {
          background-color: #f9f9f9;
          border-radius: 10px;
          padding: 12px;
          margin-top: 15px;
          box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.05);

          .evaluation-title {
            font-size: 14px;
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
            text-align: center;
            position: relative;
            
            &::after {
              content: '';
              position: absolute;
              bottom: -4px;
              left: 50%;
              transform: translateX(-50%);
              width: 40px;
              height: 2px;
              background-color: #4361ee;
              border-radius: 2px;
            }
          }

          .rating-badge {
            font-size: 24px;
            font-weight: bold;
            color: #fff;
            width: 40px;
            height: 40px;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 50%;
            margin: 0 auto 12px;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
          }

          .rating-badge.S {
            background: linear-gradient(135deg, #ff9a00, #ff4e50);
            border: 2px solid #ffb84d;
          }

          .rating-badge.A {
            background: linear-gradient(135deg, #4361ee, #3a0ca3);
            border: 2px solid #6f8dfb;
          }

          .rating-badge.B {
            background: linear-gradient(135deg, #2ecc71, #27ae60);
            border: 2px solid #6de29c;
          }

          .rating-badge.C {
            background: linear-gradient(135deg, #3498db, #2980b9);
            border: 2px solid #5dade2;
          }

          .evaluation-content {
            font-size: 12px;
            color: #666;
            line-height: 1.6;
            text-align: justify;
            white-space: pre-line;
          }
        }

        .preview-footer {
          margin-top: 15px;
          text-align: center;
          font-size: 12px;
          color: #888;
          display: flex;
          flex-direction: column;
          align-items: center;

          .qr-code {
            width: 60px;
            height: 60px;
            background-color: #f5f5f5;
            border-radius: 6px;
            margin-bottom: 8px;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
            
            &::before {
              content: 'ZEEHO';
              color: #4361ee;
              font-size: 10px;
              font-weight: bold;
            }
            
            &::after {
              content: '';
              position: absolute;
              width: 40px;
              height: 40px;
              background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%234361ee'%3E%3Cpath d='M3,3H21V21H3V3M5,5V19H19V5H5M7,7H9V9H7V7M11,7H17V9H11V7M7,11H9V13H7V11M11,11H17V13H11V11M7,15H9V17H7V15M11,15H17V17H11V15Z'/%3E%3C/svg%3E");
              background-size: contain;
            }
          }

          .brand-text {
            font-size: 12px;
            font-weight: 600;
            background: linear-gradient(90deg, #4361ee, #3a0ca3);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
          }
        }
      }
    }

    .share-actions {
      padding: 20px;
      border-top: 1px solid #eee;
      
      .share-title-small {
        font-size: 15px;
        font-weight: 500;
        color: #333;
        margin-bottom: 15px;
      }
      
      .share-options {
        display: flex;
        justify-content: space-around;
        
        .share-option {
          display: flex;
          flex-direction: column;
          align-items: center;
          
          .share-icon {
            width: 50px;
            height: 50px;
            background-color: #f5f5f5;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 8px;
            
            &:active {
              background-color: #e5e5e5;
            }
            
            &.loading {
              position: relative;
              
              .loading-spinner {
                width: 24px;
                height: 24px;
                border: 2px solid rgba(67, 97, 238, 0.2);
                border-top: 2px solid #4361ee;
                border-radius: 50%;
                animation: spin 1s linear infinite;
              }
            }
            
            &.save-icon {
              color: #4361ee;
            }
            
            &.wechat-icon {
              background-color: #f0ffe5;
            }
            
            &.moments-icon {
              background-color: #f0ffe5;
            }
            
            &.more-icon {
              color: #666;
            }
          }
          
          .share-label {
            font-size: 12px;
            color: #666;
          }
        }
      }
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>